<template>
    <div v-if="visible" class="dialog-overlay">
        <div class="dialog">
            <!-- 对话框头部 -->
            <div class="dialog-header">
                <h3>添加关系定义</h3>
                <button @click="closeDialog" class="close-button">×</button>
            </div>

            <!-- 表单主体 -->
            <div class="dialog-body">
                <form @submit.prevent="confirm">
                    <div class="form-item">
                        <label>ID</label>
                        <input v-model="relation.id" type="text" placeholder="请输入关系ID" />
                    </div>
                    <div class="form-item">
                        <label>名称</label>
                        <input v-model="relation.text" type="text" placeholder="请输入关系名称" />
                    </div>
                    <div class="form-item">
                        <label>源实体</label>
                        <select v-model="relation.source">
                            <option value="">请选择</option>
                            <option v-for="entity in entities" :key="entity.id" :value="entity.id">
                                {{ entity.text }}
                            </option>
                        </select>
                    </div>
                    <div class="form-item">
                        <label>目标实体</label>
                        <select v-model="relation.target">
                            <option value="">请选择</option>
                            <option v-for="entity in entities" :key="entity.id" :value="entity.id">
                                {{ entity.text }}
                            </option>
                        </select>
                    </div>
                    <div class="form-item">
                        <label>描述</label>
                        <input v-model="relation.description" type="text" placeholder="请输入关系描述" />
                    </div>
                    <div class="form-item">
                        <label>路径</label>
                        <input v-model="relation.path" type="text" placeholder="请输入关系路径" />
                    </div>
                    <div class="dialog-footer">
                        <button type="button" @click="closeDialog" class="cancel-button">取消</button>
                        <button type="submit" class="primary-button">确定</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { defineProps, computed, getCurrentInstance, reactive, ref, onMounted } from 'vue';

const { emit } = getCurrentInstance();

// 响应式数据
const relation = reactive({
    id: '',
    text: '',
    source: '',
    target: '',
    description: '',
    path: '/'
});

// 存储实体列表，用于源实体和目标实体的选择
const entities = ref([]);

// 在组件挂载时从localStorage加载实体数据
onMounted(() => {
    loadEntitiesFromStorage();
});

// 从localStorage加载实体数据
function loadEntitiesFromStorage() {
    try {
        const storedEntities = localStorage.getItem('entities');
        if (storedEntities) {
            entities.value = JSON.parse(storedEntities);
            console.log('从本地存储加载了', entities.value.length, '个实体用于关系选择');
        }
    } catch (error) {
        console.error('从本地存储加载实体失败:', error);
    }
}

// 对话框显示控制
const props = defineProps({ modelValue: Boolean });

const visible = computed({
    get: () => props.modelValue,
    set: (value) => {
        emit('update:modelValue', value);
    }
});

// 操作方法
const closeDialog = () => {
    visible.value = false;
    // 重置表单
    Object.assign(relation, {
        id: '',
        text: '',
        source: '',
        target: '',
        description: '',
        path: '/'
    });
};

const confirm = () => {
    // 验证必填字段
    if (!relation.id || !relation.text || !relation.source || !relation.target) {
        alert('请填写所有必填字段');
        return;
    }

    // 查找源实体和目标实体的文本
    const sourceEntity = entities.value.find(entity => entity.id === relation.source);
    const targetEntity = entities.value.find(entity => entity.id === relation.target);

    // 创建要保存的关系对象
    const relationToSave = {
        id: relation.id,
        text: relation.text,
        source: relation.source,
        target: relation.target,
        sourceText: sourceEntity ? sourceEntity.text : '未找到实体',
        targetText: targetEntity ? targetEntity.text : '未找到实体',
        description: relation.description,
        path: relation.path,
        // 添加随机背景色
        style: { 'background-color': getRandomPastelColor() }
    };

    // 发送确认事件，并传递关系数据
    emit('confirm', relationToSave);
    closeDialog();
};

// 生成随机柔和颜色
function getRandomPastelColor() {
    const hue = Math.floor(Math.random() * 360);
    return `hsl(${hue}, 90%, 70%)`;
}
</script>

<style scoped>
/* 蒙层样式 */
.dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

/* 对话框容器 */
.dialog {
    background: white;
    width: 60%;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 头部样式 */
.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: #f5f5f5;
}

.dialog-header h3 {
    margin: 0;
    font-size: 18px;
    color: rgba(0, 0, 0, 0.85);
}

.close-button {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
}

/* 表单内容区域 */
.dialog-body {
    padding: 20px;
}

.form-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

.form-item label {
    margin-right: 10px;
    font-weight: bold;
    width: 80px;
    /* 固定宽度以对齐 */
}

.form-item input,
.form-item select {
    flex: 1;
    padding: 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

/* 底部操作区 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 15px;
    background: #f5f5f5;
}

/* 按钮样式 */
.primary-button {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    cursor: pointer;
    border-radius: 4px;
    margin-left: 10px;
}

.cancel-button {
    background-color: #f0f0f0;
    color: #333;
    border: none;
    padding: 8px 16px;
    cursor: pointer;
    border-radius: 4px;
}

.primary-button:hover {
    background-color: #66b1ff;
}

.cancel-button:hover {
    background-color: #e0e0e0;
}
</style>
